package superminer.xinfang.com.ipreport.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import superminer.xinfang.com.ipreport.R;
import superminer.xinfang.com.ipreport.activity.LoginActivity;
import superminer.xinfang.com.ipreport.activity.Main2Activity;
import superminer.xinfang.com.ipreport.adapter.LogAdapter;
import superminer.xinfang.com.ipreport.base.BaseApplication;
import superminer.xinfang.com.ipreport.bean.IPChangeBean;
import superminer.xinfang.com.ipreport.bean.IpReportBean;
import superminer.xinfang.com.ipreport.bean.LoginBean;
import superminer.xinfang.com.ipreport.network.TcpNetHelper;
import superminer.xinfang.com.ipreport.util.MyGson;
import superminer.xinfang.com.ipreport.util.SPUtil;
import superminer.xinfang.com.ipreport.util.ToastUtil;
import superminer.xinfang.com.ipreport.util.netty.INettyClient;
import superminer.xinfang.com.ipreport.util.netty.NettyClient;
import superminer.xinfang.com.ipreport.view.dialog.LoadingDialog;
import superminer.xinfang.com.ipreport.view.lazyviewpager.LazyFragmentPagerAdapter;

import static superminer.xinfang.com.ipreport.R.id.edit_password;
import static superminer.xinfang.com.ipreport.R.id.edit_phone;

/**
 * ip设置fragment 一个一个
 * Created by Administrator on 2019/3/5.
 */

public class IpSettingFragment extends Fragment implements LazyFragmentPagerAdapter.Laziable {

    private INettyClient.OnDataReceiveListener onDataReceiveListener;

    private LoadingDialog loadingDialog;
    private boolean isFirst = true;//是否是第一次获取的
    //当前ip
    @BindView(R.id.edit_a1)
    TextView edit_a1;
    @BindView(R.id.edit_a2)
    TextView edit_a2;
    @BindView(R.id.edit_a3)
    TextView edit_a3;
    @BindView(R.id.edit_a4)
    TextView edit_a4;


    //要修改ip
    @BindView(R.id.edit_b1)
    EditText edit_b1;
    @BindView(R.id.edit_b2)
    EditText edit_b2;
    @BindView(R.id.edit_b3)
    EditText edit_b3;
    @BindView(R.id.edit_b4)
    EditText edit_b4;

    @BindView(R.id.listview)
    ListView listView;

    @BindView(R.id.btn_sub)
    TextView btn_sub;
    @BindView(R.id.btn_next)
    TextView btn_next;


    private List<String> stringList;
    private LogAdapter logAdapter;





    @OnClick({R.id.btn_sub, R.id.btn_next})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_sub://q确认修改
                if (check()) {
                    btn_sub.setBackgroundResource(R.drawable.btn_gary_bg);
                    btn_next.setBackgroundResource(R.drawable.btn_gary_bg);

                    String reIP = edit_a1.getText().toString().trim() + "." + edit_a2.getText().toString().trim() + "." + edit_a3.getText().toString().trim() + "." + edit_a4.getText().toString().trim();
                    String nowIP = edit_b1.getText().toString().trim() + "." + edit_b2.getText().toString().trim() + "." + edit_b3.getText().toString().trim() + "." + edit_b4.getText().toString().trim();
                    logAdapter.additem("正在修改IP:" + reIP + "-->" + nowIP);
//                    loadingDialog.show();
                    TcpNetHelper.changeIP(reIP, nowIP);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            btn_sub.setBackgroundResource(R.drawable.btn_system_bg);
                            btn_next.setBackgroundResource(R.drawable.btn_system_bg);
                        }
                    }, 8000);


                }
                break;

            case R.id.btn_next://下一台
                edit_a1.setText("0");
                edit_a2.setText("0");
                edit_a3.setText("0");
                edit_a4.setText("0");
                if (!edit_b4.getText().toString().trim().equals("")) {
                    int integer = Integer.valueOf(edit_b4.getText().toString().trim());
                    if (integer < 255) {
                        edit_b4.setText(integer + 1 + "");
                    } else {
                        edit_b4.setText("" + integer);
                    }
                }

                logAdapter.additem("下一台矿机");
                break;


        }
    }


    private boolean check() {

        if ("0".equals(edit_a1.getText().toString().trim())) {
            logAdapter.additem("未检测到矿机，无法修改IP");
//            ToastUtil.showToast(getActivity(), "未检测到矿机，无法修改");
            return false;
        }
        if (edit_b1.getText().toString().trim().equals("")) {
            ToastUtil.showToast(getActivity(), "请填写要修改IP");
            return false;
        }
        if (edit_b2.getText().toString().trim().equals("")) {
            ToastUtil.showToast(getActivity(), "请填写要修改IP");
            return false;
        }
        if (edit_b3.getText().toString().trim().equals("")) {
            ToastUtil.showToast(getActivity(), "请填写要修改IP");
            return false;
        }
        if (edit_b4.getText().toString().trim().equals("")) {
            ToastUtil.showToast(getActivity(), "请填写要修改IP");
            return false;
        }
        if (Integer.valueOf(edit_b1.getText().toString().trim()) > 255) {
            edit_b1.setText("" + 255);
            ToastUtil.showToast(getActivity(), "IP最大255");
            return false;
        }
        if (Integer.valueOf(edit_b2.getText().toString().trim()) > 255) {
            edit_b2.setText("" + 255);
            ToastUtil.showToast(getActivity(), "IP最大255");
            return false;
        }
        if (Integer.valueOf(edit_b3.getText().toString().trim()) > 255) {
            edit_b3.setText("" + 255);
            ToastUtil.showToast(getActivity(), "IP最大255");
            return false;
        }
        if (Integer.valueOf(edit_b4.getText().toString().trim()) > 255) {
            edit_b4.setText("" + 255);
            ToastUtil.showToast(getActivity(), "IP最大255");
            return false;
        }
        return true;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_ipsetting, container, false);
        ButterKnife.bind(this, view);
        loadingDialog = new LoadingDialog(getActivity(), 0);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);


        setSetDataReceiveListener();
        initListview();

        initEdit();

    }

    private void initEdit() {
        edit_b1.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.length() != 0 && (charSequence.charAt(charSequence.length() - 1) + "").equals(".")) {
                    String substring = charSequence.toString().substring(0, charSequence.length() - 1);
                    edit_b1.setText(substring);
                    edit_b2.requestFocus();
                }
//                else if (charSequence.toString().length()==3)
//                   {
//                       edit_b2.requestFocus();
//                   }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });


        edit_b2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                Log.i("-->", "edit_b2的数据：" + charSequence);
                if (charSequence.length() != 0 && (charSequence.charAt(charSequence.length() - 1) + "").equals(".")) {
                    Log.i("-->", "edit_b2的2数据：" + charSequence);
                    String substring = charSequence.toString().substring(0, charSequence.length() - 1);
                    edit_b2.setText(substring);
                    edit_b3.requestFocus();
                }
//                else if (charSequence.toString().length()==3)
//                {
//                    edit_b3.requestFocus();
//                }

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        edit_b3.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.length() != 0 && (charSequence.charAt(charSequence.length() - 1) + "").equals(".")) {
                    String substring = charSequence.toString().substring(0, charSequence.length() - 1);
                    edit_b3.setText(substring);
                    edit_b4.requestFocus();
                }
//                else if (charSequence.toString().length()==3)
//                {
//                    edit_b4.requestFocus();
//                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });


    }

    private void initListview() {
        stringList = new ArrayList<>();
        logAdapter = new LogAdapter(stringList, getActivity());
        listView.setAdapter(logAdapter);


    }


    private String[] macs = {"", "", ""};//储存三个mac
    private int n = 0;

    //当前mac是否在数组里
    private boolean isYes(String macAddress) {
        if (macAddress.equals(macs[0])) {
            return true;
        }
        if (macAddress.equals(macs[1])) {
            return true;
        }
        if (macAddress.equals(macs[2])) {
            return true;
        }
        return false;
    }


    /**
     * 设置数据监听
     */
    private void setSetDataReceiveListener() {
        onDataReceiveListener = new INettyClient.OnDataReceiveListener() {
            @Override
            public void onDataReceive(int mt, String jsons) {

                loadingDialog.dismiss();
                Log.i("-->", "IpSettingFragment返回数据：" + mt + " json:" + jsons);

                //矿机发送IP信息
                if (mt == TcpNetHelper.IpReport) {

                    IpReportBean ipReportBean = MyGson.getInstance().fromJson(jsons, IpReportBean.class);
                    if (!isYes(ipReportBean.getMacAddress())) {


                        logAdapter.additem("收到当前IP：" + ipReportBean.getIP());
                        String[] split = ipReportBean.getIP().toString().split("\\.");
                        if (split.length == 4) {
                            edit_a1.setText("" + split[0]);
                            edit_a2.setText("" + split[1]);
                            edit_a3.setText("" + split[2]);
                            edit_a4.setText("" + split[3]);

                            if (isFirst) {
                                edit_b1.setText("" + split[0]);
                                edit_b2.setText("" + split[1]);
                                edit_b3.setText("" + split[2]);
                                String lastip = "" + split[3];
                                int lastipint = Integer.valueOf(lastip);
                                if (lastipint < 254) {
                                    edit_b4.setText(lastipint + 1 + "");
                                } else {
                                    edit_b4.setText("" + lastipint);
                                }

                            }
                            isFirst = false;

                        }

                        macs[n] = ipReportBean.getMacAddress();
                        final int i = n;
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {

                                macs[i] = "";
                            }
                        }, 12000);

                        n = (n + 1) % 3;
                    }
                }
                //修改IP结果
                if (mt == TcpNetHelper.ReChangeIP && ((Main2Activity) getActivity()).getNowNUm() == 0) {
//                      loadingDialog.dismiss();
                    IPChangeBean ipChangeBean = MyGson.getInstance().fromJson(jsons, IPChangeBean.class);
                    btn_sub.setBackgroundResource(R.drawable.btn_system_bg);
                    btn_next.setBackgroundResource(R.drawable.btn_system_bg);
                    if (ipChangeBean.isIsSuccess()) {
                  
//                        logAdapter.additem(ipChangeBean.getMessage() + " " + reIP + "-->" + nowIP);
                        ToastUtil.showToast(getActivity(), "" + ipChangeBean.getMessage());
                        edit_a1.setText("0");
                        edit_a2.setText("0");
                        edit_a3.setText("0");
                        edit_a4.setText("0");
                        int integer = Integer.valueOf(edit_b4.getText().toString().trim());
                        if (integer < 255) {
                            edit_b4.setText(integer + 1 + "");
                        } else {
                            edit_b4.setText("" + integer);
                        }

                    } else {
//                        logAdapter.additem(ipChangeBean.getMessage() + " " + reIP + "-->" + nowIP);
                        ToastUtil.showToast(getActivity(), "" + ipChangeBean.getMessage());
                    }
                }
                if (mt == TcpNetHelper.UNLOGIN) {
                    //登录异常
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                    getActivity().finish();
                }


            }
        };
        if (onDataReceiveListener != null)
            NettyClient.getInstance().addDataReceiveListener(onDataReceiveListener);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        //解除绑定
        NettyClient.getInstance().delectDataReceiveListener(onDataReceiveListener);
    }
}
